package k1;

import java.sql.*;
import java.util.Scanner;

    public class msql {
        public static void sql() throws Exception {

            Scanner sc=new Scanner(System.in);

            //注册驱动
            //DriverManager.registerDriver(new Driver());会注册两次，在new Driver的静态代码块里
            //字符串-->提取外部配置文件
            Class.forName("com.mysql.cj.jdbc.Driver");//可以出发类的加载，触发静态代码块注册
            String url="jdbc:mysql://localhost:3306/mysql1";


            Connection con = DriverManager.getConnection(url,  "root", "2022");
            //sql语句
            String denglu="select * from user where name =? and id =? ;";

            //创建执行对象 statement 会出错
            PreparedStatement s1 = con.prepareStatement(denglu);
            System.out.println("请输入名字");
            String name=sc.nextLine();
            System.out.println("请输入id");
            String id=sc.nextLine();
            s1.setObject( 1,name);
            s1.setObject( 2,id);
            //返回结果
            ResultSet r = s1.executeQuery();
            //获取数据  类似迭代器
            if( r.next()){
                System.out.println("登陆成功");

                System.out.print  ( r.getString(1)+"---");
                System.out.print  ( r.getString(2)+"---");
                System.out.print  ( r.getString(3)+"---");

            }else  System.out.println("登陆失败");
            System.out.println("请输入新名字");
            String newname=sc.nextLine();
            System.out.println("请输入新id");
            String newid=sc.nextLine();
            System.out.println("请输入新密码");
            String newpassward=sc.nextLine();
            String insert="insert into user values(?,?,?)";
            PreparedStatement s2 = con.prepareStatement(insert);
            s2.setObject(1,newname);
            s2.setObject(2,newid);
            s2.setObject(3, newpassward );
            int i = s2.executeUpdate();
            if(i==1)System.out.println("增加成功");
            //关闭资源
            r.close();s1.close();s2.close();con.close();
        }
        }
